import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/community_info.dart';
import '../data.dart';

class CommunityStorageService {
  static const String _storageKey = 'community_info_list';
  final SharedPreferences _prefs;

  CommunityStorageService(this._prefs);

  // 获取所有小区信息
  Future<List<CommunityInfo>> getAllCommunities() async {
    final String? jsonString = _prefs.getString(_storageKey);
    if (jsonString == null || jsonString.isEmpty) {
      // 如果没有数据或数据为空，加载默认数据
      final defaultCommunities = DefaultCommunityData.getDefaultCommunities();
      await _saveCommunities(defaultCommunities);
      return defaultCommunities;
    }

    try {
      final List<dynamic> jsonList = json.decode(jsonString);
      if (jsonList.isEmpty) {
        // 如果解析后的数据为空，加载默认数据
        final defaultCommunities = DefaultCommunityData.getDefaultCommunities();
        await _saveCommunities(defaultCommunities);
        return defaultCommunities;
      }
      return jsonList.map((json) => CommunityInfo.fromJson(json)).toList();
    } catch (e) {
      print('解析数据失败: $e');
      // 如果解析失败，加载默认数据
      final defaultCommunities = DefaultCommunityData.getDefaultCommunities();
      await _saveCommunities(defaultCommunities);
      return defaultCommunities;
    }
  }

  // 保存小区信息
  Future<void> saveCommunity(CommunityInfo community) async {
    final List<CommunityInfo> communities = await getAllCommunities();
    final index = communities.indexWhere((c) => c.id == community.id);

    if (index >= 0) {
      // 更新现有记录
      communities[index] = community;
    } else {
      // 添加新记录
      communities.add(community);
    }

    await _saveCommunities(communities);
  }

  // 删除小区信息
  Future<void> deleteCommunity(String id) async {
    final List<CommunityInfo> communities = await getAllCommunities();
    communities.removeWhere((c) => c.id == id);
    await _saveCommunities(communities);
  }

  // 删除所有小区信息
  Future<void> deleteAllCommunities() async {
    await _prefs.remove(_storageKey);
  }

  // 保存所有小区信息到本地存储
  Future<void> _saveCommunities(List<CommunityInfo> communities) async {
    final jsonList = communities.map((c) => c.toJson()).toList();
    await _prefs.setString(_storageKey, json.encode(jsonList));
  }

  // 生成唯一ID
  String generateId() {
    return DateTime.now().millisecondsSinceEpoch.toString();
  }
} 